﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Drawing;
using System.Drawing.Imaging;
using IML.MVC.Models;
using IML;


namespace IML.MVC.Controllers
{
    [HandleError]
    public class HomeController : Controller
    {
        private static string _source { get; set; }

        [HttpPost]
        public ActionResult Index(string captcha)
        {
            if (captcha == HttpContext.Session["captcha"].ToString())
                ViewData["Message"] = "CAPTCHA challenge was successful!";
            else
                ViewData["Message"] = "CAPTCHA challenge failed - please try again!";

            return View();
        }

        public ActionResult Index()
        {
            ViewData["Message"] = "Links to IML Documents and Downloadables.";

            return View();
        }

        public ActionResult Try()
        {
            ViewData["true"] = false;
            return View();
        }

        [HttpPost]
        public ActionResult Try(string source)
        {
            ViewData["true"] = true;
            if (string.IsNullOrEmpty(source))
            {
                _source = "Error";
                ModelState.AddModelError("_FORM", "Source code cannot be empty");
            }
            else
            {
                _source = source;
            }
            return View();
        }

        public ActionResult Flag()
        {
            var temp = float.Parse("-10");
            var color = ColorTranslator.FromHtml("244,234,34,54");
            try
            {
                return new IMLResult();
            }
            catch (Exception ex)
            {
                return new CaptchaResult(ex.Message);
            }
        }

        public ActionResult Image()
        {
            try
            {
                return new IMLResult(_source);
            }
            catch (Exception ex)
            {
                return new ErrorImageResult(ex.Message, 700, 500);
            }
        }

        public CaptchaResult GetCaptcha()
        {
            string captchaText = Captcha.GenerateRandomCode();
            HttpContext.Session.Add("captcha", captchaText);
            return new CaptchaResult(captchaText);
        }
    }
}
